package com.workflow.service.impl;

import java.util.Date;
import java.util.List;

import com.common.util.AbstractManager;
import com.common.util.DateHelper;
import com.common.util.PagerModel;
import com.workflow.bean.Salesdept;
import com.workflow.service.SalesdeptService;

public class SalesdeptServiceImpl extends AbstractManager implements
		SalesdeptService {

	public void addSalesdept(Salesdept salesdept) {
		StringBuilder salesno = new StringBuilder();
		Long count = 0L;
		String hql = "select count(*) from Salesdept";
		count = (Long) this.getHibernateTemplate().find(hql).get(0);
		count %= 1000L;
		
		Long num = Long.parseLong(DateHelper.dateToStr(new Date(), "yyyyMMddHms"));
		num *= 1000L;		
		num += count;
		
		salesno.append(salesdept.getDepartmentByDeptcode().getDeptcode());
		salesno.append("-XS-");
		salesno.append(num);
		
		salesdept.setSalesno(salesno.toString());
		salesdept.setStartdate(new Date());
		
		this.getHibernateTemplate().save(salesdept);
	}

	@SuppressWarnings("unchecked")
	public List<Salesdept> findAllSalesdept() {
		String hql = "from Salesdept sd order by sd.departmentByDeptcode.deptcode ,sd.salesno ";
		return this.getHibernateTemplate().find(hql);
	}

	public Salesdept findSalesdept(String salesno) {
		return (Salesdept) this.getHibernateTemplate().load(Salesdept.class, salesno);
	}

	public PagerModel findSalesdeptForPager() {
		String hql = "from Salesdept sd order by sd.departmentByDeptcode.deptcode ,sd.salesno ";
		return searchPaginated(hql);
	}

	public PagerModel findSalesdeptForPager(String deptcode) {
		if(deptcode == "") {
			return findSalesdeptForPager();
		}
		
		String hql = "from Salesdept sd where sd.departmentByDeptcode.deptcode = ? order by sd.salesno ";
		return searchPaginated(hql,deptcode);
	}

	public void removeSalesdept(String salesno) {
		String hql = "from Salesdeptdetail sdd where sdd.salesdept.salesno = ? ";
		List list = (List)this.getHibernateTemplate().find(hql);
		
		if(list == null || list.size() == 0 ) {
			Salesdept salesdept = (Salesdept) this.getHibernateTemplate().load(Salesdept.class, salesno);
			this.getHibernateTemplate().delete(salesdept);
		}
	}

	public void updateSalesdept(Salesdept salesdept) {
		this.getHibernateTemplate().update(salesdept);
	}
}
